package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.feignclient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @ClassName: PasswordAuthServiceImpl
 * @Description: 账号密码认证
 * @Author: Huang Yao
 * @CreateTime: 2024-07-17 15:54
 * @Version: 1.0
 **/
@Service(value = "nocheckcode_authservice")
public class NoCheckcodeAuthServiceImpl implements AuthService {
    @Autowired
    private XcUserMapper xcUserMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    CheckCodeClient checkCodeClient;
    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        // 校验验证码
        // String checkcode = authParamsDto.getCheckcode();
        // String checkcodekey = authParamsDto.getCheckcodekey();
        // if(StringUtils.isBlank(checkcode) || StringUtils.isBlank(checkcodekey))
        // {
        //     throw new RuntimeException("验证码为空");
        // }
        // Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
        // if(!verify){
        //     throw new RuntimeException("验证码输入错误");
        // }
        //账号
        String username = authParamsDto.getUsername();
        //根据username查询数器库
        XcUser user = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>()
                .eq(StringUtils.isNotBlank(username), XcUser::getUsername, username));
        //查询到用户不存在，要返回null即可，spring security框架抛出异常用户不存在
        if(user == null)
        {
            throw new RuntimeException("账号不存在");
        }
        //校验密码正确性
        String passwordDb = user.getPassword();
        String passwordForm = authParamsDto.getPassword();
        if(!passwordEncoder.matches(passwordForm,passwordDb)){
            throw new RuntimeException("账号或密码错误");
        }
        XcUserExt userExt = new XcUserExt();
        BeanUtils.copyProperties(user,userExt);
        return userExt;
    }
}
